package cn.xjfcloud.onedriveserver.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {
	/**
	 * 获取下载的inputstream
	 * 
	 * @param downloadUrl
	 * @return
	 * @throws IOException
	 */
	public static InputStream getDownloadInputStream(String downloadUrl) throws IOException {
		URL url = new URL(downloadUrl);
		URLConnection conn = url.openConnection();
		InputStream inStream = conn.getInputStream();
		return inStream;
	}

	/**
	 * 断点续传,开始为0, 202 代表片段上传完成，201代表最后一个片段上传完成
	 * 
	 * @param content
	 * @param url
	 * @param offset
	 * @param total
	 * @return
	 * @throws IOException
	 */
	public static Map<String, String> uploadFileRange(byte[] content, String url, Long offset, Long total) throws IOException {
		OkHttpClient client = new OkHttpClient().newBuilder().readTimeout(20, TimeUnit.SECONDS).build();
		RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), content);
	
		//System.out.println(content.length);
		//System.out.println("bytes " + offset + "-" + (offset + content.length-1) + "/" + total);

		Request request = new Request.Builder().addHeader("Content-Length", String.valueOf(content.length))
				.addHeader("Content-Range", " bytes " + offset + "-" + (offset + content.length-1) + "/" + total).url(url)
				.put(fileBody).build();
	
		//执行并获取response
		Response response = client.newCall(request).execute();
		String responseString = response.body().string();
		//System.out.println(responseString);
		Integer code = response.code();
		Map<String, String> resultMap = new HashMap<String, String>();
		resultMap.put("response", responseString);
		resultMap.put("code", code.toString());
		return resultMap;
	}
}
